/**
* @Author: jianglei
* @Date:   2017-10-12 12:06:49
*/
'use strict'
import Vue from 'vue'
export default function treeToArray(data, expandAll, parent = null, level = null) {
  let tmp = []
  Array.from(data).forEach(function(record) {
    if (record._expanded === undefined) {
      Vue.set(record, '_expanded', expandAll)
    }
    let _level = 1
    if (level !== undefined && level !== null) {
      _level = level + 1
    }
    Vue.set(record, '_level', _level)
    // 如果有父元素
    if (parent) {
      Vue.set(record, 'parent', parent)
    }
    tmp.push(record)
    if (record.children && record.children.length > 0) {
      const children = treeToArray(record.children, expandAll, record, _level)
      tmp = tmp.concat(children)
    }
  })
  return tmp
}



// 树形数据转换工具
/**
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @param pKey
 * @returns {*}
 */
 export default function translateDataToTree(list, pKey = 'parent_id') {
    let data = JSON.parse(JSON.stringify(list))
    const parent = data.filter(
      (value) =>
        value[pKey] === 'undefined' || value[pKey] == null || value[pKey] == 0
    )
    const children = data.filter(
      (value) =>
        value[pKey] !== 'undefined' && value[pKey] != null && value[pKey] > 0
    )
    const translator = (parent, children) => {
      parent.forEach((parent) => {
        children.forEach((current, index) => {
          if (current[pKey] === parent.pk_id) {
            const temp = JSON.parse(JSON.stringify(children))
            temp.splice(index, 1)
            translator([current], temp)
            typeof parent.children !== 'undefined'
              ? parent.children.push(current)
              : (parent.children = [current])
          }
        })
      })
    }
    translator(parent, children)
    return parent
  }
  
  /**
   * @description 树形结构数据转换成父子关系的数组
   * @param data
   * @returns {[]}
   */
  export default function translateTreeToData(list) {
    let data = JSON.parse(JSON.stringify(list))
    const result = []
    data.forEach((item) => {
      const loop = (data) => {
        const child = data.children
        if (child) {
          for (let i = 0; i < child.length; i++) {
            loop(child[i])
          }
          delete data.children
        }
        result.push(data)
      }
      loop(item)
    })
    return result
  }
 
